package com.mrobuy.jdvc.service.impl;

import com.gavel.utils.StringUtils;
import com.mrobuy.jdvc.dao.CommonDao;
import com.mrobuy.jdvc.entity.*;
import com.mrobuy.jdvc.model.CategoryInfo;
import com.mrobuy.jdvc.service.VCCategoryService;
import com.mrobuy.util.IdentifierGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import sun.security.util.Cache;

import java.util.List;

@Service("vcCategoryService")
public class VCCategoryServiceImpl implements VCCategoryService {

    private static Logger LOG = LoggerFactory.getLogger(VCCategoryService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CommonDao commonDao;

    //第一个参数表示cache对象中允许添加的键值对数量，第二个参数表示缓存的时间，单位是秒
    private static Cache<String, CategoryInfo> idCache = Cache.newHardMemoryCache(0,3600);

    private static Cache<String, CategoryInfo> nameCache = Cache.newHardMemoryCache(0,3600);

    @Override
    public CategoryInfo loadCategoryInfo(String id) {

        if (StringUtils.isBlank(id)) {
            return null;
        }

        CategoryInfo categoryInfo = idCache.get(StringUtils.trim(id));
        if ( categoryInfo!=null  ) {
            return categoryInfo;
        }

        categoryInfo = loadById(StringUtils.trim(id));
        if ( categoryInfo!=null ) {
            idCache.put(String.valueOf(categoryInfo.getId()), categoryInfo);
            nameCache.put(StringUtils.trim(categoryInfo.getName()), categoryInfo);
        }

        return categoryInfo;
    }

    /**
     *  提交上架商品的属性值
     *
     * @param item
     * @param propid
     * @param value
     */
    @Override
    public void commit(VCShelvesItem item, String propid, String value) {

        if ( item==null || StringUtils.isBlank(item.getCid1()) ) {
            return;
        }

        CategoryInfo categoryInfo = loadCategoryInfo(item.getCid1());
        if ( categoryInfo==null ) {
            return;
        }

        for (VCCategoryProp categoryProp : categoryInfo.getProps()) {
            if ( categoryProp.getPropid().equalsIgnoreCase(propid) ) {
                System.out.println(categoryProp);
                // 规格属性值

                String code = item.getCode();

                VCItemPropValue propValue = null;
                try {
                    propValue =  jdbcTemplate.queryForObject("select * from VC_ITEM_PROP_VALUE where PRODUCTID = ? and  PROPID = ? ", new BeanPropertyRowMapper<>(VCItemPropValue.class), code, propid);
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e.getCause());
                }

                if ( propValue==null ) {
                    propValue = new VCItemPropValue();
                    propValue.setId(IdentifierGen.uuid());
                    propValue.setProductid(code);
                    propValue.setPropid(Integer.parseInt(categoryProp.getPropid()));
                    propValue.setPropname(categoryProp.getPropname());
                    propValue.setType(categoryProp.getInputtype());
                    propValue.setRequired(categoryProp.getRequired());
                    commonDao.insert(propValue);
                }

                switch ( categoryProp.getInputtype() ) {
                    case "1":
                        propValue.setPropvid(getPropValueByValue(categoryProp.getPropid(), value));
                        break;
                    case "2":
                        propValue.setPropvalues(getPropValueByValue(categoryProp.getPropid(), value));
                        break;
                     default:
                            propValue.setPropremark(value);
                }

                commonDao.update(propValue);
                return;
            }
        }

        for (VCCategoryExtProp categoryExtProp : categoryInfo.getExtProps()) {
            if ( categoryExtProp.getAttId().equalsIgnoreCase(propid) ) {
                System.out.println(categoryExtProp);
                // 扩展属性

                String code = StringUtils.trim(item.getType()) + "-" + StringUtils.trim(item.getSkucode());

                VCItemExtPropValue propValue = null;
                try {
                    propValue =  jdbcTemplate.queryForObject("select * from VC_ITEM_EXT_PROP_VALUE where PRODUCTID = ? and PROPID = ? ", new BeanPropertyRowMapper<>(VCItemExtPropValue.class), code, propid);
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e.getCause());
                }

                if ( propValue==null ) {
                    propValue = new VCItemExtPropValue();
                    propValue.setId(IdentifierGen.uuid());
                    propValue.setProductid(code);
                    propValue.setPropid(Integer.parseInt(categoryExtProp.getAttId()));
                    propValue.setPropname(categoryExtProp.getName());
                    propValue.setType(categoryExtProp.getInputType());
                    propValue.setRequired(categoryExtProp.getIsRequired());
                    commonDao.insert(propValue);
                }

                switch ( categoryExtProp.getInputType() ) {
                    case "1":
                    case "2":
                        propValue.setExtvalue(getExtPropValueByValue(Integer.parseInt(categoryExtProp.getAttId()), value));
                        break;
                    default:
                        propValue.setExtremark(value);
                }
                commonDao.update(propValue);
                return;
            }
        }
    }

    private String getPropValueByValue(String propid, String value){

        VCPropValue propValue = null;
        try {
            propValue =  jdbcTemplate.queryForObject("select * from VC_PROP_VALUE where PROPID = ? and VALUENAME = ? ", new BeanPropertyRowMapper<>(VCPropValue.class), propid, value);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e.getCause());
        }

        return (propValue==null ? "" : String.valueOf(propValue.getValueId()));
    }

    private String getExtPropValueByValue(Integer propid, String value){
        VCExtPropValue propValue = null;
        try {
            propValue =  jdbcTemplate.queryForObject("select * from VC_EXTPROP_VALUE where PROPID = ? and VALUENAME = ? ", new BeanPropertyRowMapper<>(VCExtPropValue.class), propid, value);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e.getCause());
        }

        return (propValue==null ? "" : String.valueOf(propValue.getValueId()));
    }

    private CategoryInfo loadById(String id){
        if (StringUtils.isBlank(id)) {
            return null;
        }

        CategoryInfo categoryInfo = null;
        try {
            categoryInfo =  jdbcTemplate.queryForObject("select * from VC_CATEGORY where ID = ? ", new BeanPropertyRowMapper<>(CategoryInfo.class), id);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e.getCause());
        }

        if ( categoryInfo==null ) {
            return null;
        }

        List<VCCategoryProp> categoryProps = jdbcTemplate.query("select * from VC_CATEGORY_PROP where CID = ? ", new BeanPropertyRowMapper<>(VCCategoryProp.class), id);
        categoryInfo.setProps(categoryProps);

        List<VCCategoryExtProp> categoryExtProps = jdbcTemplate.query("select * from VC_CATEGORY_EXTPROP where CID = ? ", new BeanPropertyRowMapper<>(VCCategoryExtProp.class), id);
        categoryInfo.setExtProps(categoryExtProps);

        List<VCCategorySaleProp> categorySaleProps = jdbcTemplate.query("select * from VC_CATEGORY_SALE_PROP where CID = ? ", new BeanPropertyRowMapper<>(VCCategorySaleProp.class), id);
        categoryInfo.setSaleProps(categorySaleProps);

        return categoryInfo;
    }
}
